//
//  VOCWordTestViewController.m
//  iVoc
//
//  Created by Wallace Wu on 09-3-23.
//  Copyright 2009 Sonic Solutions. All rights reserved.
//

#import "VOCWordTestViewController.h"
#import "VocListController.h"
#import "VOCResultViewController.h"

#define ITEM_FINISH         1
#define ITEM_SHOW           2


@implementation VOCWordTestViewController

@synthesize currentList;
@synthesize resumePausedTest;
@synthesize testLanguage;


// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
        // hide tabbar
        self.hidesBottomBarWhenPushed = YES;
    }
    return self;
}


/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {                                                                                                                                                                                                                                                                                                                   
}
*/

-(void)pauseAndBack:(id)sender
{
    //save current status
    if(![currentTest pauseTest])
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"ERROR",nil)
                                                        message:NSLocalizedString(@"TEST_NOT_SAVED",nil)
                                                        delegate:nil 
                                                        cancelButtonTitle:NSLocalizedString(@"OK",nil) 
                                                        otherButtonTitles:nil];
        [alert show];
        [alert release];
    }
    //return to main list
    for (UIViewController *mainView in [self.navigationController viewControllers]) {
        if([mainView isKindOfClass:[VocListController class]])
        {
            [self.navigationController popToViewController:mainView animated:YES];
        }
    }
}

-(void)finishTest
{
    // end test and show statistics of current test
    [currentTest stopTest];
    
    if([timer isValid])
    {
        [timer invalidate];
        [timer release];
        timer = nil;
    }
    
    VOCResultViewController *resultViewController = [[VOCResultViewController alloc] initWithNibName:@"VOCResultViewController" bundle:nil];
    resultViewController.rightTimes = currentTest.rightTimes;
    resultViewController.wrongTimes = currentTest.wrongTimes;
    [self.navigationController pushViewController:resultViewController animated:YES];
    [resultViewController release];
}

- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item
{
    if(item.tag == ITEM_FINISH)
    {
        [self finishTest];
    }
    else if(item.tag = ITEM_SHOW)
    {
        NSUInteger aWrongChoice = (currentTest.rightChoice-1)>=0?currentTest.rightChoice-1:currentTest.choiceLimit;
        [self clickedChoice:choiceButtons[aWrongChoice]];
    }
}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
    UITabBarItem *finish = [[UITabBarItem alloc] initWithTitle:@"Finish" image:[UIImage imageNamed:@"finish.png"] tag:ITEM_FINISH];
    UITabBarItem *rightAnswer = [[UITabBarItem alloc] initWithTitle:NSLocalizedString(@"HELP_ME",nil) image:[UIImage imageNamed:@"help.png"] tag:ITEM_SHOW];
    
    NSArray *itemArray = [NSArray arrayWithObjects:finish,rightAnswer,nil];
    bottomBar.items = itemArray;
    
    [finish release];
    [rightAnswer release];
    
    bottomBar.delegate = self;
    
    UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithTitle:@"Back" style:UIBarButtonItemStylePlain target:self action:@selector(pauseAndBack:)];
    self.navigationItem.leftBarButtonItem = back;
    [back release];
        
    if(self.resumePausedTest)
    {
        currentTest = [[VOCWordTest pausedTest] retain];
    }
    else
    {
        currentTest = [[VOCWordTest alloc] initWithWordList:self.currentList];
        currentTest.choiceLimit = 4; 
        currentTest.testLanguage = self.testLanguage;
    }

    [currentTest startTest];
    NSArray *choices = currentTest.currentChoices;
    wordLabel.text = currentTest.currentWord.word;
    
    CGRect startPoint = CGRectMake(80, 80, 160, 40);
    for (int i = 0; i < CHOICE_NUMBER; i++) {
        choiceButtons[i] = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        choiceButtons[i].frame = startPoint;
        choiceButtons[i].tag = i;
        [choiceButtons[i] addTarget:self action:@selector(clickedChoice:) forControlEvents:UIControlEventTouchDown];
        choiceButtons[i].font = [UIFont systemFontOfSize:14];
        [self.view addSubview:choiceButtons[i]];
        [self.view bringSubviewToFront:choiceButtons[i]];
        startPoint = CGRectOffset(startPoint, 0, 70);
    }
        
    NSUInteger i, count = [choices count];
    for (i = 0; i < count; i++) {
        VOCWordExp *exp = (VOCWordExp*)[choices objectAtIndex:i];
        
        [choiceButtons[i] setTitle:exp.explanation forState:UIControlStateNormal];
    }
    
}

-(void)clickedChoice:(id)sender
{
    if([timer isValid])
    {
        return;
    }
    [currentTest makeChoice:((UIButton*)sender).tag];
    
    // tell user the right answer on UI
    UIImage *rightAnswer = [UIImage imageNamed:@"rightAnswer.png"];
    [choiceButtons[currentTest.rightChoice] setBackgroundImage:rightAnswer forState:UIControlStateNormal];
    
    timer = [[NSTimer scheduledTimerWithTimeInterval:2.0 target:self selector:@selector(nextTest:) userInfo:nil repeats:(BOOL)NO] retain];
    
    for (int i = 0; i < CHOICE_NUMBER; i++) {
        [choiceButtons[i] removeTarget:self action:@selector(clickedChoice:) forControlEvents:UIControlEventTouchDown];
    }
}

-(void)nextTest:(NSTimer*)theTimer
{
    if([currentTest hasEndTest])
    {
        [self finishTest];
        return;
    }
    
    [choiceButtons[currentTest.rightChoice] setBackgroundImage:nil forState:UIControlStateNormal];
    [currentTest next];
    NSArray *nextChoices = currentTest.currentChoices;
    
    NSUInteger i, count = [nextChoices count];
    for (i = 0; i < count; i++) {
        VOCWordExp *exp = (VOCWordExp*)[nextChoices objectAtIndex:i];
        
        [choiceButtons[i] setTitle:exp.explanation forState:UIControlStateNormal];
    }
    
    wordLabel.text = currentTest.currentWord.word;
    for (int i = 0; i < CHOICE_NUMBER; i++) {
        [choiceButtons[i] addTarget:self action:@selector(clickedChoice:) forControlEvents:UIControlEventTouchDown];
    }
    
    [timer release];
    timer = nil;
}
    
/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview
    // Release anything that's not essential, such as cached data
}


- (void)dealloc {
    [bottomBar release];
    [wordLabel release];
    [timer   release];
    [self.currentList release];
    [currentTest release];
    [super dealloc];
}


@end
